package org.liyufeng.project.servlet;


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.liyufeng.project.util.ParamesAPI;
import org.liyufeng.project.util.CommonUtil;
import org.liyufeng.project.util.OAuth2Util;


public class OAuth2Servlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  request.setCharacterEncoding("UTF-8");
		  response.setCharacterEncoding("UTF-8"); 
		  PrintWriter out = response.getWriter();
		  //用户同意授权后，能获取到code
		  String code = request.getParameter("code"); 
		  String state = request.getParameter("state");
		  
		  if (!"authdeny".equals(code)) {
		  String access_token = CommonUtil.getToken(ParamesAPI.corpId, ParamesAPI.corpsecret).getAccessToken();
		  // agentid 跳转链接时所在的企业应用ID 管理员须拥有agent的使用权限；agentid必须和跳转链接时所在的企业应用ID相同
		  String UserID = OAuth2Util.GetUserID(access_token, code, ParamesAPI.payrollPersonalAgentId);
		  //设置要传递的参数
		  request.setAttribute("UserID", UserID);
		  }
		  else{
			  out.print("授权获取失败，至于为什么，自己找原因。。。");
		  }
		  
		  // 跳转到个人工资表jsp页面
		  if(state.equals("payrollPersonal")){
			  request.getRequestDispatcher("payrollPersonal.jsp").forward(request, response);
		  }else if(state.equals("payrollDepartment")){
			  request.getRequestDispatcher("payrollDepartment.jsp").forward(request, response);
		 }
		}	

}
